<template>
    <ContentBase>
        <div class="content">
            <div class="content-top">
                <div class="input-group flex-nowrap" style="margin-bottom: 20px;">
                    <span class="input-group-text" id="title" style="font-weight: bold;">标题</span>
                    <input type="text" class="form-control" v-model="title" placeholder="请输入标题">
                </div>
                <div class="mb-3">
                    <label for="formFile" class="form-label" style="font-weight: bold;">上传文件</label>
                    <!-- 绑定 file 选择器 -->
                    <input class="form-control" type="file" id="formFile" @change="onFileChange">
                </div>
            </div>
            <div class="content-bottom">
                <div style="color: red;">{{ error_message }}</div>
                <button type="button" class="btn btn-outline-primary btn-lg" @click="clickToSubmit">提交</button>
            </div>
        </div>
    </ContentBase>
</template>

<script setup>
import ContentBase from '@/components/ContentBase';
import $ from 'jquery';
import { useStore } from 'vuex';
import router from '@/router/index';
import { ref } from 'vue';

const store = useStore();
const error_message = ref(null);
const title = ref(null);
const file = ref(null); // 用于保存文件

const clearMessage = () => {
    error_message.value = null;
}

// 获取文件并保存
const onFileChange = (event) => {
    file.value = event.target.files[0];
}

const clickToSubmit = () => {
    error_message.value = null;

    const formData = new FormData();
    formData.append('title', title.value);
    formData.append('file', file.value);

    $.ajax({
        url: "http://localhost:3000/api/manage/material/add-material", // 后端接口
        type: "POST",
        data: formData,
        processData: false, // 防止 jQuery 处理数据
        contentType: false, // 不设置 contentType 让浏览器自动处理
        headers: {
            'Authorization': "Bearer " + store.state.user.token,
        },
        success(resp) {
            if (resp.error_message === "success") {
                router.push({ name: "MaterialDownload" });
            } else {
                error_message.value = resp.error_message;
                setTimeout(clearMessage, 4000);
            }
        },
        error(resp) {
            console.log(resp);
        }
    });
}

</script>

<style scoped>

.content {
    padding: 30px;
}

.content-top {
    margin-bottom: 20px;
}

.content-bottom {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
}

</style>